//
//  JYJMusicPlayerTools.m
//  HappyListen
//
//  Created by 冀永金 on 16/9/6.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJMusicPlayerTools.h"
#import "JYJProgramModel.h"
#import "JYJBestMuscicListModel.h"
#import "JYJMusicsContentModel.h"
#import "JYJChannelModel.h"
#import "JYJMusicsModel.h"
@interface JYJMusicPlayerTools ()
@property (nonatomic, strong) NSTimer *timer;// 滑动条定时器
@property (nonatomic, strong) NSURL *url;
@end
@implementation JYJMusicPlayerTools
+ (instancetype)shareMusicPlayerTools {
    static JYJMusicPlayerTools *mpTools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mpTools = [[JYJMusicPlayerTools alloc]init];
    });
    return mpTools;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        self.player = [[AVPlayer alloc]init];
        //为播放完毕添加观察者   播放完毕的操作  有外边决定
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endPlay:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
// 播放完毕
- (void)endPlay:(NSNotification *)nati {
    //播放完毕先让音乐停止
    [self pauseMusic];
    if ([self.delegate respondsToSelector:@selector(endPlayAction)]) {
        [self.delegate endPlayAction];
    }
}
// 准备播放
- (void)preparePlayMusic {
    // 只要AVPlayer有currentTime,那么一定有观察者
    // 所以直接移除
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }
    
    
    self.playerItem= [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:self.programModel.music_media]];
    
        
   

    //为item的status添加观察者
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld  context:nil];
    //用新建的item,替换AVPlayer之前的item,新的item添加了观察者
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        switch ([[change valueForKey:@"new"] integerValue]) {
            case AVPlayerItemStatusUnknown:
                NSLog(@"不知道什么错误");
                break;
            case AVPlayerItemStatusReadyToPlay:
                // 只有观察到status变为这种状态,才会真正的播放.
                [self playMusic];
                break;
            case AVPlayerItemStatusFailed:
                // mini设备不插耳机或者某些耳机会导致准备失败.
                NSLog(@"准备失败");
                if ([self.delegate respondsToSelector:@selector(playFail)]) {
                    [self.delegate playFail];
                    
                }
                break;
            default:
                break;
        }
    }
    
    

}
// 播放
- (void)playMusic {
    //如果定时器已经存在，说明已经在播放中，直接返回
    // 对于已经存在的定时器，只有pauseMusic方法才会使之停止和销毁
    if (self.timer != nil) {
        return;
    }
    // 播放后开启定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [self.player play];
}
- (void)timerAction:(NSTimer *)timer {
    //!!!!!!!!计时器的处理方法中，不断的调用代理方法，将音乐播放器的进度返回出去
    [self.delegate getCurTime:[self valueToString:[self getCurrentTime]] totle:[self valueToString:[self getTotalTime]] progress:[self getProgress]];
}
// 获取当前时间 (！！！！！就是这个算法 别问我为什么   规定的)
- (NSInteger)getCurrentTime {
    if (self.player.currentItem) {
        // 当前的时间value / 当前时间的时间比例
        return self.player.currentTime.value / self.player.currentTime.timescale;
    }
    return 0;
}
- (NSInteger)getTotalTime {
    CMTime totalTime = [self.player.currentItem duration];
    if (totalTime.timescale == 0) {
        return 1;
    }else {
        return totalTime.value / totalTime.timescale;
    }
}

// 获取当前播放进度
- (CGFloat)getProgress {
    return (CGFloat) [self getCurrentTime] / (CGFloat)[self getTotalTime];
}
// 将整数转化为00：00格式
- (NSString *)valueToString:(NSInteger)value {
    return [NSString stringWithFormat:@"%.2ld:%.2ld",value / 60,value % 60];
}


- (void)pauseMusic {
    [self.timer invalidate];
    self.timer = nil;
    [self.player pause];
}
// 跳转方法
- (void)seekToTimeWithValue:(CGFloat)value {
    // 跳转之前先停止
    [self.player pause];
    //跳转
    [self.player seekToTime:CMTimeMake(value * [self getTotalTime], 1) completionHandler:^(BOOL finished) {
        if (finished == YES) {
            [self.player play];
        }
    }];
}
@end
